//
//  TestResultDetailTableViewCell.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/6/2.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "TestResultDetailTableViewCell.h"


@implementation TestResultDetailTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    self.contentView.backgroundColor = lWhiteColor;
    self.backgroundColor = lWhiteColor;
    [self.contentView addSubview:self.backView];
    [PlayManager sharPlayManager].delegate = self;
    [self.backView addSubview:self.titleImg];
    [self.backView addSubview:self.scoreLabel];
    
    [self.backView addSubview:self.wLabel];
    [self.backView addSubview:self.lLabel];
    [self.backView addSubview:self.zLabel];
    
    [self.backView addSubview:self.questionLabel];
    
    [self.backView addSubview:self.recordViewPlay];
    [self.backView addSubview:self.recordView];
    
    [self.backView addSubview:self.titleRecordLabel];
    
    [self.backView addSubview:self.myRecordViewPlay];
    [self.backView addSubview:self.myRecordView];
    
    [self.backView addSubview:self.titleAnswerLabel];
    [self.backView addSubview:self.answerLabel];
    
    self.contentView.backgroundColor = lClearColor;
    self.backgroundColor = lClearColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetNoPlay:) name:@"playerStatueChange" object:nil];
    return self;
   
    // Initialization code
}
-(void)resetNoPlay:(NSNotification *)notic
{
    if (notic.object != self) {
        self.recordViewPlay.selected = self.myRecordViewPlay.selected = NO;
        self.viewModel.audioPlay = NO;
        self.viewModel.myAudioPlay = NO;
    }
}
- (UILabel *)wLabel
{
    if (!_wLabel) {
        
        _wLabel = [[UILabel alloc] init];
        _wLabel.frame = CGRectMake(10,28, 75,24);
        _wLabel.font = MFontWithSize(14);
        _wLabel.textColor = rgba(51, 51, 51, 1);
        _wLabel.textAlignment = NSTextAlignmentLeft;
        _wLabel.text = @"流利度：";
        
    }
    return _wLabel;
}
- (UILabel *)lLabel
{
    if (!_lLabel) {
        
        _lLabel = [[UILabel alloc] init];
        _lLabel.frame = CGRectMake(_wLabel.right + 32,28, 75,24);
        _lLabel.font = MFontWithSize(14);
        _lLabel.textColor = rgba(51, 51, 51, 1);
        _lLabel.textAlignment = NSTextAlignmentLeft;
        _lLabel.text = @"惠州初中英语";
        
    }
    return _lLabel;
}
- (UILabel *)zLabel
{
    if (!_zLabel) {
        
        _zLabel = [[UILabel alloc] init];
        _zLabel.frame = CGRectMake(_lLabel.right + 32,28, 75,24);
        _zLabel.font = MFontWithSize(14);
        _zLabel.textColor = rgba(51, 51, 51, 1);
        _zLabel.textAlignment = NSTextAlignmentLeft;
        _zLabel.text = @"准确度：";
        
    }
    return _zLabel;
}
- (UILabel *)questionLabel
{
    if (!_questionLabel) {
        
        _questionLabel = [[UILabel alloc] init];
        _questionLabel.frame = CGRectMake(10,self.wLabel.bottom + 10, self.backView.width - 20,CGFLOAT_MIN);
        _questionLabel.numberOfLines = 0;
        _questionLabel.font = MFontWithSize(16);
        _questionLabel.textColor = rgba(51, 51, 51, 1);
        _questionLabel.textAlignment = NSTextAlignmentLeft;
        _questionLabel.text = @"惠州初中英语";
        
    }
    return _questionLabel;
}
- (UILabel *)titleRecordLabel
{
    if (!_titleRecordLabel) {
        
        _titleRecordLabel = [[UILabel alloc] init];
        _titleRecordLabel.frame = CGRectMake(10,self.recordViewPlay.bottom + 8, self.backView.width - 20,32);
        _titleRecordLabel.font = MFontWithSize(16);
        _titleRecordLabel.textColor = rgba(142, 142, 142, 1);
        _titleRecordLabel.textAlignment = NSTextAlignmentLeft;
        _titleRecordLabel.text = @"我的录音";
        
    }
    return _titleRecordLabel;
}
- (UILabel *)titleAnswerLabel
{
    if (!_titleAnswerLabel) {
        
        _titleAnswerLabel = [[UILabel alloc] init];
        _titleAnswerLabel.frame = CGRectMake(10,self.myRecordViewPlay.bottom + 8, self.backView.width - 20,32);
        _titleAnswerLabel.font = MFontWithSize(16);
        _titleAnswerLabel.textColor = rgba(51, 51, 51, 1);
        _titleAnswerLabel.textAlignment = NSTextAlignmentLeft;
        _titleAnswerLabel.text = @"参考答案";
        
    }
    return _titleAnswerLabel;
}
- (UILabel *)answerLabel
{
    if (!_answerLabel) {
        
        _answerLabel = [[UILabel alloc] init];
        _answerLabel.frame = CGRectMake(10,self.titleAnswerLabel.bottom + 10, self.backView.width - 20,CGFLOAT_MIN);
        _answerLabel.numberOfLines = 0;
        _answerLabel.font = MFontWithSize(16);
        _answerLabel.textColor = rgba(51, 51, 51, 1);
        _answerLabel.textAlignment = NSTextAlignmentLeft;
        _answerLabel.text = @"惠州初中英语";
        
    }
    return _answerLabel;
}
- (UILabel *)scoreLabel
{
    if (!_scoreLabel) {
        
        _scoreLabel = [[UILabel alloc] init];
        _scoreLabel.frame = CGRectMake(45,1,self.backView.width - 45 - 10,22);
        _scoreLabel.font = MFontWithSize(14);
        _scoreLabel.textColor = rgba(51, 51, 51, 1);
        _scoreLabel.textAlignment = NSTextAlignmentLeft;
        _scoreLabel.text = @"(0.60分/1.5分)";
        
    }
    return _scoreLabel;
}

- (UIImageView *)titleImg
{
    if (!_titleImg) {
        _titleImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 26, 16)];
        _titleImg.image = IMAGENAMED(@"ic_result_half_right");
    }
    return _titleImg;
}
- (UIImageView *)attImg
{
    if (!_attImg) {
        _attImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, lScreenWidth - 40, 16)];
        [self.backView addSubview:_attImg];
    }
    return _attImg;
}
- (AudioPlayProgressView *)recordView
{
    if (!_recordView) {
        _recordView = [[AudioPlayProgressView alloc] initWithFrame:CGRectMake(36, self.questionLabel.bottom + 13, self.backView.width - 38 - 32, 22) Progress:0.8];
    }
    return _recordView;
}
- (AudioPlayProgressView *)myRecordView
{
    if (!_myRecordView) {
        _myRecordView = [[AudioPlayProgressView alloc] initWithFrame:CGRectMake(36, self.titleRecordLabel.bottom + 13, self.backView.width - 38 - 32, 22) Progress:0.8];
    }
    return _myRecordView;
}
- (UIButton *)recordViewPlay
{
    if (!_recordViewPlay) {
        _recordViewPlay = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(8, self.questionLabel.bottom + 13, 22, 22);
            
            [button setImage:[UIImage imageNamed:@"ic_audio_play_stop"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_audio_play_play"] forState:UIControlStateSelected];
            button;
        });
        
        [_recordViewPlay addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _recordViewPlay;
}
- (UIButton *)myRecordViewPlay
{
    if (!_myRecordViewPlay) {
        _myRecordViewPlay = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(8, self.titleRecordLabel.bottom + 13, 22, 22);
            
            [button setImage:[UIImage imageNamed:@"ic_audio_play_stop"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_audio_play_play"] forState:UIControlStateSelected];
            button;
        });
        
        [_myRecordViewPlay addTarget:self action:@selector(playMyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _myRecordViewPlay;
}
- (UIView *)backView
{
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake( 10, 0, lScreenWidth - 20, 294)];
        _backView.backgroundColor = lWhiteColor;
        
    }
    return _backView;
}
#pragma mark -- event

- (void)setViewModel:(TestSubCellViewModel *)viewModel{
    _viewModel = viewModel;
    self.questionModel = viewModel.question;
    
    self.myRecordView.hidden = self.titleRecordLabel.hidden = self.myRecordViewPlay.hidden = NO;
   
    self.recordView.hidden =  self.recordViewPlay.hidden = NO;
    if (self.questionModel.recordUrl.length != 0) {
        self.myRecordView.progress = viewModel.myAudioProgress;
        if (viewModel.myAudioTimeAll <= 0) {
            dispatch_queue_t t = dispatch_queue_create("my", nil);
            dispatch_async(t, ^{
                [MethodTool getAudioMp3TimeWithUrl:self.questionModel.recordUrl complete:^(double time) {
                    viewModel.myAudioTimeAll = time;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.myRecordView.timeLabel.text = [NSString stringWithFormat:@"%@ / %@",[MethodTool getPlayTimeWithTime:viewModel.myAudioTimeAll*viewModel.myAudioProgress],[MethodTool getPlayTimeWithTime:viewModel.myAudioTimeAll]];
                    });
                }];
            });
        }
        self.myRecordView.timeLabel.text = [NSString stringWithFormat:@"%@ / %@",[MethodTool getPlayTimeWithTime:viewModel.myAudioTimeAll*viewModel.myAudioProgress],[MethodTool getPlayTimeWithTime:viewModel.myAudioTimeAll]];
        self.myRecordViewPlay.selected = viewModel.myAudioPlay;
    }else{
        self.myRecordView.hidden = self.titleRecordLabel.hidden = self.myRecordViewPlay.hidden = YES;
    }
   
    HSQuestion *testModel = self.questionModel;
    NSString *aUrl = @"";
    if (testModel.trunk.attachments.count != 0) {
        
        HSValueAttachment *k= testModel.trunk.attachments[0];
        for (HSValueAttachment *att in testModel.trunk.attachments) {
            if (att.fileType == 2) {
                k = att;
            }
        }
        aUrl = [NSString stringWithFormat:@"%@%@",self.resmain,k.url];
    }
    if (aUrl.length != 0) {
        self.recordView.progress = viewModel.myAudioProgress;
        if (viewModel.audioTimeAll <= 0) {
            dispatch_queue_t t = dispatch_queue_create("my", nil);
            dispatch_async(t, ^{
                [MethodTool getAudioMp3TimeWithUrl:aUrl complete:^(double time) {
                    viewModel.audioTimeAll = time;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.recordView.timeLabel.text = [NSString stringWithFormat:@"%@ / %@",[MethodTool getPlayTimeWithTime:viewModel.audioTimeAll*viewModel.audioProgress],[MethodTool getPlayTimeWithTime:viewModel.audioTimeAll]];
                    });
                }];
            });
        }
        self.recordView.timeLabel.text = [NSString stringWithFormat:@"%@ / %@",[MethodTool getPlayTimeWithTime:viewModel.audioTimeAll*viewModel.audioProgress],[MethodTool getPlayTimeWithTime:viewModel.audioTimeAll]];
        self.recordViewPlay.selected = viewModel.audioPlay;
    }else{
        self.recordView.hidden =  self.recordViewPlay.hidden = YES;
    }
    
    if (self.viewModel.audioPlay||self.viewModel.myAudioPlay) {
        [PlayManager sharPlayManager].delegate = self;
    }
    
    NSString *score = [NSString stringWithFormat:@"%.1f",self.questionModel.questionRefSorce]; ;
    double fscore = self.questionModel.score;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%@分/%.1f分)",score,fscore]];
    [att addAttribute:NSForegroundColorAttributeName value:rgba(250, 25, 44, 1) range:NSMakeRange(1, score.length + 1)];
    
    self.scoreLabel.attributedText =  att;
    
    self.wLabel.attributedText =  [self getAttWithText:@"完成度" Text2:[NSString stringWithFormat:@"%.f",self.questionModel.integrityscore]];
    self.lLabel.attributedText =  [self getAttWithText:@"流利度" Text2:[NSString stringWithFormat:@"%.f",self.questionModel.fluencyscore]];
    self.zLabel.attributedText =  [self getAttWithText:@"准确度" Text2:[NSString stringWithFormat:@"%.f",self.questionModel.accuracyscore]];
    
    self.questionLabel.text = self.questionModel.trunk.body;
    [self.questionLabel sizeToFit];
    self.questionLabel.width = self.backView.width - 20;
    self.answerLabel.text = self.questionModel.answer;
    self.answerLabel.width = self.backView.width - 20;
    [self.answerLabel sizeToFit];
    double y = self.questionLabel.bottom + 10;
    self.attImg.hidden = YES;
    if (viewModel.img) {
        self.attImg.hidden = NO;
        self.attImg.image = viewModel.img;
        self.attImg.y = y;
        self.attImg.height =  viewModel.img.size.height/viewModel.img.size.width*(SCREEN_W - 40);
        y = self.attImg.bottom + 13;
    }
   
    if (!self.recordViewPlay.hidden) {
        self.recordView.y = y;
        self.recordViewPlay.y = y;
        y = self.recordViewPlay.bottom + 8;
    }
   
    
    if (!self.myRecordViewPlay.hidden) {
        self.titleRecordLabel.y = y;
        y = self.titleRecordLabel.bottom + 13;
        self.myRecordView.y = y;
        self.myRecordViewPlay.y = y;
        y = self.myRecordViewPlay.bottom + 8;
    }
   
    self.titleAnswerLabel.y = y;
    self.answerLabel.y = self.titleAnswerLabel.bottom + 10;
    self.backView.height = viewModel.rowHeight;
    
}

- (void)playButtonClick:(UIButton *)sender {
    
    HSQuestion *testModel = self.questionModel;
    NSString *aUrl = @"";
    if (testModel.trunk.attachments.count != 0) {
        
        HSValueAttachment *k= testModel.trunk.attachments[0];
        for (HSValueAttachment *att in testModel.trunk.attachments) {
            if (att.fileType == 2) {
                k = att;
            }
        }
        aUrl = [NSString stringWithFormat:@"%@%@",self.resmain,k.url];
    }
    if (IsStrEmpty(aUrl)) return;
    sender.selected = !sender.selected;
    self.viewModel.audioPlay = sender.selected;
    if (sender.selected) {
        [self playWithUrl:aUrl];
    }else{
        [[PlayManager sharPlayManager] pause];
    }
    self.myRecordViewPlay.selected = NO;
    self.viewModel.myAudioPlay = NO;
    
}
- (void)playMyButtonClick:(UIButton *)sender {
    if (IsStrEmpty(self.questionModel.recordUrl)) return;
    sender.selected = !sender.selected;
    self.viewModel.myAudioPlay = sender.selected;
    if (sender.selected) {
        [self playWithUrl:self.questionModel.recordUrl];
    }else{
        [[PlayManager sharPlayManager] pause];
    }
    self.recordViewPlay.selected = NO;
    self.viewModel.audioPlay = NO;
}
- (void)playWithUrl:(NSString *)url
{
    [PlayManager sharPlayManager].delegate = self;
    [[PlayManager sharPlayManager] playerWithURL:url];
}
- (void)playerWithPlayer:(AVPlayer *)player progress:(float)progress duration:(float)duration currentTime:(float)currentTime
{
    
    if (self.myRecordViewPlay.selected) {
        self.viewModel.myAudioProgress = progress;
        self.myRecordView.progress = progress;
        self.myRecordView.timeLabel.text = [NSString stringWithFormat:@"%@ / %@",[MethodTool getPlayTimeWithTime:currentTime],[MethodTool getPlayTimeWithTime:duration]];
    }
    if (self.recordViewPlay.selected) {
        self.recordView.progress = progress;
        self.viewModel.audioProgress = progress;
        self.recordView.timeLabel.text = [NSString stringWithFormat:@"%@ / %@",[MethodTool getPlayTimeWithTime:currentTime],[MethodTool getPlayTimeWithTime:duration]];
    }
}
- (void)musicFinsh
{
    self.recordViewPlay.selected = self.myRecordViewPlay.selected = NO;
    self.viewModel.audioPlay = NO;
    self.viewModel.myAudioPlay = NO;
}

- (NSMutableAttributedString *)getAttWithText:(NSString *)text1 Text2:(NSString *)text2
{
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@：%@",text1,text2]];
    [att addAttribute:NSForegroundColorAttributeName value:rgba(250, 25, 44, 1) range:[att.string rangeOfString:text2]];
    return att;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
